package cn.lcfms.cms;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.ListIterator;

import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.lcfms.bin.core.Application;

public abstract class CollectResult extends CollctBase{
	protected Collect collect ;
	public abstract boolean _do(HashMap<String, String> content);
	public CollectResult(Collect collect) {
		this.collect=collect;
	}
	//获取图片
	protected String getImg(String content) {
		Document doc = Jsoup.parse(content);
		Elements a = doc.select("img[src]");
		ListIterator<Element> iterator = a.listIterator();
		URL _url;
		try {
			_url = new URL(collect.getNowUrl());
		} catch (MalformedURLException e) {
			return content;
		}
		String path=_url.getProtocol()+"://"+_url.getHost()+_url.getFile();
		path=path.substring(0, path.lastIndexOf("/"))+"/";
		String host=_url.getProtocol()+"://"+_url.getHost()+"/";
		while (iterator.hasNext()) {
			Element next = iterator.next();
			String attr = next.attr("src");
			if(attr.startsWith("/")) {
				attr=host+attr.substring(1);
			}
			if(attr.startsWith("./")) {			
				attr=path+attr.substring(2);
			}
			if(!attr.startsWith("http")) {
				attr=path+attr;
			}	
			try {
				byte[] browser = CollctBase.browser(attr, collect.getBean().getCookie());
				String shortfile = CollctBase.getFileName(attr);
				String filepath=Application.ROOT_PATH+"uploadfile"+Application.F+"images"+Application.F+shortfile.charAt(0)+Application.F+shortfile;
				File file=new File(filepath);
				if(!file.exists()) {
					FileUtils.writeByteArrayToFile(file, browser);
				}			
				//next.attr("src",Application.APP_PATH+"uploadfile/images/"+shortfile.charAt(0)+"/"+shortfile);
				next.attr("src","/uploadfile/images/"+shortfile.charAt(0)+"/"+shortfile);
			} catch (IOException e) {
				continue;
			}
		}
		return doc.select("body").html();
	}
		
	//删除超链接
	protected String deleteA(String content) {
		return content;
	}
	
	protected void setMsg(boolean success,String msg) {
		collect.setSuccess(success);
		collect.setMsg(collect.getNowUrl()+"，"+msg);	
	}
}
